//
//  WPAddNewReturnCaseVC.m
//  wobingwoyi
//
//  Created by WGP on 2016/12/28.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPAddNewReturnCaseVC.h"
#import "HMDatePicker.h"
#import "TZImagePickerController.h"
#import "WPCustomTextAttachment.h"
#import "YBPopupMenu.h"
#import "WPCredentialsEditeTableViewCell.h"

#define MARGIN 20.0
@interface WPAddNewReturnCaseVC ()<HMDatePickerDelegate,TZImagePickerControllerDelegate,UITextViewDelegate,YBPopupMenuDelegate,UITextFieldDelegate>

@property(nonatomic,strong)UIView *bgView;

@property(nonatomic,strong)UIView *statusView;
@property(nonatomic,strong)UIView *navView;
@property(nonatomic,strong)UIView *baseInfoView;
@property(nonatomic,strong)UIView *topView;
@property(nonatomic,strong)UILabel *timeLabel;
//@property(nonatomic,strong)UIView *bgScrollView;

@property(nonatomic,strong)UIButton *treamentStateBtn;
@property(nonatomic,strong)UIButton *ZXBtn;
@property(nonatomic,strong)UILabel *diseaseLabel;
@property(nonatomic,strong)UILabel *doctorLabel;
@property(nonatomic,strong)UILabel *hospitalLabel;
@property(nonatomic,strong)UITextField *diseaseTextField;
@property(nonatomic,strong)UITextField *doctorTextField;
@property(nonatomic,strong)UITextField *hospitalTextField;
@property(nonatomic,strong)YBPopupMenu *ZXPopupMenu;
@property(nonatomic,strong)NSArray *treamentArr;
@property(nonatomic,strong)NSArray *ZXArr;

@property(nonatomic,strong)NSMutableArray *locations;
@property(nonatomic,assign)CGRect oldFrame;

@property(nonatomic,assign)CGFloat keyboardH;
@property(nonatomic,assign)int index;
@property(nonatomic,assign)BOOL isSaved;

@property(nonatomic,strong)NSArray *timesArr;

@end

@implementation WPAddNewReturnCaseVC

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [IQKeyboardManager sharedManager].enable = NO;
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    [IQKeyboardManager sharedManager].enable = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.index = 1;
    
    UIImage *ZDImage = [UIImage imageNamed:@"zhenduan"];
    self.oldFrame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-162-ZDImage.size.height-108);
    
    //注册通知,监听键盘弹出事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardWillShowNotification object:nil];
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    self.title = @"编辑诊断单";
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"back_normal"] forState:UIControlStateNormal];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"back_highlight"] forState:UIControlStateHighlighted];
    [backBtn addTarget:self action:@selector(backBtnDidClick) forControlEvents:UIControlEventTouchUpInside];
    [backBtn sizeToFit];
    
    UIBarButtonItem *btn_left = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]   initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace   target:nil action:nil];
    /**
     width为负数时，相当于btn向右移动width数值个像素，由于按钮本身和  边界间距为5pix，所以width设为-5时，间距正好调整为0；width为正数 时，正好相反，相当于往左移动width数值个像素
     */
    negativeSpacer.width = -8;
    self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:negativeSpacer, btn_left, nil];
    
    UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    [saveBtn setTitleColor:GloballightFontColor forState:UIControlStateHighlighted];
    [saveBtn addTarget:self action:@selector(saveBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [saveBtn setTitleColor:GLobalFontColor forState:UIControlStateNormal];
    saveBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [saveBtn sizeToFit];
    UIBarButtonItem *btn_right = [[UIBarButtonItem alloc] initWithCustomView:saveBtn];
    
    UIBarButtonItem *nsr = [[UIBarButtonItem alloc]   initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace   target:nil action:nil];
    nsr.width = -8;
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:negativeSpacer,btn_right, nil];
    
        [self setupUI];
}

-(void)setupUI
{
    [self baseInfoView];
    [self topView];
    [self textView];
}

-(UIView *)baseInfoView
{
    if (_baseInfoView == nil)
    {
        self.view.backgroundColor = [UIColor whiteColor];
        self.bgView = [UIView new];
        [self.view addSubview:self.bgView];
        self.bgView.frame = CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64);
        self.bgView.backgroundColor  = [UIColor whiteColor];
        
        UIImage *ZDImage = [UIImage imageNamed:@"zhenduan"];
        
        _baseInfoView = [UIView new];
        _baseInfoView.backgroundColor = [UIColor whiteColor];
        [self.bgView addSubview:_baseInfoView];
        [_baseInfoView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.equalTo(self.bgView);
            make.height.mas_equalTo(162+ZDImage.size.height);
        }];
        
        self.treamentStateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.treamentStateBtn setTitle:@"治疗状态" forState:UIControlStateNormal];
        [self.treamentStateBtn setTitleColor:RGB_COLOR(208, 208, 213) forState:UIControlStateNormal];
        [_baseInfoView addSubview:self.treamentStateBtn];
        [self.treamentStateBtn addTarget:self action:@selector(timeBtnDidClick:) forControlEvents:UIControlEventTouchDown];
        self.treamentStateBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        CGSize size = [self.treamentStateBtn.titleLabel.text sizeWithMaxSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) font:14];
        [self.treamentStateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(size.width+1);
            make.right.equalTo(_baseInfoView).offset(-8);
            make.top.equalTo(_baseInfoView);
            make.height.mas_equalTo(44);
        }];
        
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"treamentState"]];
        [_baseInfoView addSubview:imageView];
        
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.treamentStateBtn);
            make.right.equalTo(self.treamentStateBtn.mas_left).offset(-8);
            make.width.mas_equalTo(15);
            make.height.mas_equalTo(20);
        }];
        
        UIImageView *lineView = [[UIImageView alloc] init];
        lineView.backgroundColor = GLobalLineColor;
        [_baseInfoView addSubview:lineView];
        
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(0.5);
            make.height.mas_equalTo(24);
            make.centerY.equalTo(imageView);
            make.right.equalTo(imageView.mas_left).offset(-10);
        }];
        
        self.ZXBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.ZXBtn setBackgroundImage:[UIImage imageNamed:@"ZX_normal"] forState:UIControlStateNormal];
        [self.ZXBtn setBackgroundImage:[UIImage imageNamed:@"ZX_highlight"] forState:UIControlStateHighlighted];
        [self.ZXBtn setTitle:@"西医" forState:UIControlStateNormal];
        [self.ZXBtn setTitleColor:RGB_SAME(102) forState:UIControlStateNormal];
        self.ZXBtn .titleLabel.font = [UIFont systemFontOfSize:12];
        [self.ZXBtn addTarget:self action:@selector(timeBtnDidClick:) forControlEvents:UIControlEventTouchDown];
        [_baseInfoView addSubview:self.ZXBtn];
        
        UIImage *image = [UIImage imageNamed:@"ZX_normal"];
        [self.ZXBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.treamentStateBtn);
            make.right.equalTo(lineView).offset(-10);
            make.width.mas_equalTo(image.size.width);
        }];
        
        UIView *ZDView = [UIView new];
        ZDView.backgroundColor = GlobalBgColor;
        [_baseInfoView addSubview:ZDView];
        [ZDView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(_baseInfoView);
            make.height.mas_equalTo(ZDImage.size.height+30);
        }];
        UIImageView *ZDImageView = [[UIImageView alloc] initWithImage:ZDImage];
        [_baseInfoView addSubview:ZDImageView];
        [ZDImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_baseInfoView).offset(10);
            make.centerY.equalTo(ZDView);
        }];
        UILabel *ZDLabel = [UILabel new];
        ZDLabel.textColor = GLobalFontColor;
        ZDLabel.font = [UIFont systemFontOfSize:15];
        ZDLabel.text = @"诊断单";
        [_baseInfoView addSubview:ZDLabel];
        [ZDLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(ZDView);
            make.left.equalTo(ZDImageView.mas_right).offset(10);
        }];
        
        UIImageView *lineView1 = [UIImageView lineImageView];
        UIImageView *lineView2 = [UIImageView lineImageView];
        UIImageView *lineView3 = [UIImageView lineImageView];
        UIImageView *lineView4 = [UIImageView lineImageView];
        [_baseInfoView addSubview:lineView1];
        [_baseInfoView addSubview:lineView2];
        [_baseInfoView addSubview:lineView3];
        [_baseInfoView addSubview:lineView4];
        lineView1.frame = CGRectMake(10, 44, SCREEN_WIDTH-10, 0.5);
        lineView2.frame = CGRectMake(10, 88, SCREEN_WIDTH-10, 0.5);
        lineView3.frame = CGRectMake(0, 132, SCREEN_WIDTH, 0.5);
        [lineView4 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(_baseInfoView);
            make.height.mas_equalTo(0.5);
        }];
        
        [self setupLabels];
        [self setupTextFields];
    }
    return _baseInfoView;
}

-(void)setupLabels
{
    UILabel *firstLabel = [self labelWith:@"疾病名称:"];
    self.diseaseLabel = firstLabel;
    UILabel *secondLabel = [self labelWith:@"诊治医生:"];
    self.doctorLabel = secondLabel;
    UILabel *fourthLabel = [self labelWith:@"治疗医院:"];
    self.hospitalLabel = fourthLabel;
    
    
    [_baseInfoView addSubview:firstLabel];
    [_baseInfoView addSubview:secondLabel];
    [_baseInfoView addSubview:fourthLabel];
    
    CGSize size = [firstLabel.text sizeWithMaxSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) font:15];
    CGFloat margin = (44-size.height)/2.0;
    
    [firstLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_baseInfoView).offset(10);
        make.width.mas_equalTo(size.width+1);
        make.top.equalTo(_baseInfoView).offset(margin);
    }];
    
    [secondLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.width.equalTo(firstLabel);
        make.top.equalTo(firstLabel.mas_bottom).offset(2*margin);
    }];
    
    [fourthLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.width.equalTo(firstLabel);
        make.top.equalTo(secondLabel.mas_bottom).offset(2*margin);
    }];
    
}

-(void)setupTextFields
{
    self.diseaseTextField = [self textFieldWithPlaceholder:@"请输入疾病名称"];
    self.doctorTextField = [self textFieldWithPlaceholder:@"请输入诊治医生"];
    self.hospitalTextField = [self textFieldWithPlaceholder:@"请输入治疗医院"];
    
    [_baseInfoView addSubview:self.diseaseTextField];
    [_baseInfoView addSubview:self.doctorTextField];
    [_baseInfoView addSubview:self.hospitalTextField];
    
    [self.diseaseTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(42);
        make.centerY.equalTo(self.diseaseLabel);
        make.right.equalTo(self.ZXBtn.mas_left).offset(5);
        make.left.equalTo(self.diseaseLabel.mas_right).offset(8);
    }];
    
    [self.doctorTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.height.equalTo(self.diseaseTextField);
        make.right.equalTo(_baseInfoView).offset(-10);
        make.centerY.equalTo(self.doctorLabel);
    }];
    
    [self.hospitalTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.height.equalTo(self.diseaseTextField);
        make.right.equalTo(_baseInfoView).offset(-10);
        make.centerY.equalTo(self.hospitalLabel);
    }];
}

-(UIView *)topView
{
    if (_topView == nil)
    {
        _topView = [[UIView alloc] init];
        _topView.backgroundColor = [UIColor whiteColor];
        [self.bgView addSubview:_topView];
        
        [_topView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.view);
            make.top.equalTo(self.baseInfoView.mas_bottom);
            make.height.mas_equalTo(44);
        }];
        //        _topView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 44);
        
        UIImageView *bottomLine = [UIImageView lineImageView];
        [_topView addSubview:bottomLine];
        
        
        [bottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(_topView);
            make.height.mas_equalTo(0.5);
        }];
        
        _timeLabel = [UILabel new];
        _timeLabel.textColor = GLobalFontColor;
        _timeLabel.text = [NSString stringWithFormat:@"%@诊时间:",self.timesArr[self.newRank-1]];
        _timeLabel.font = [UIFont systemFontOfSize:15];
        [_topView addSubview:_timeLabel];
        
        [_timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_topView).offset(10);
            make.centerY.equalTo(_topView);
        }];
        
        _timeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _timeBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        

        NSString *timeStr = @"请输入诊断时间";
        [_timeBtn setTitleColor:RGB_COLOR(208, 208, 213) forState:UIControlStateNormal];

        [_timeBtn setTitle:timeStr forState:UIControlStateNormal];
        [_timeBtn addTarget:self action:@selector(timeBtnDidClick:) forControlEvents:UIControlEventTouchDown];
        [_topView addSubview:_timeBtn];
        
        [_timeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_topView);
            make.left.equalTo(_timeLabel.mas_right).offset(8);
        }];
        
        UIButton *addPictureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [addPictureBtn setTitle:@"添加图片" forState:UIControlStateNormal];
        addPictureBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [addPictureBtn setTitleColor:GLobalFontColor forState:UIControlStateNormal];
        [addPictureBtn setTitleColor:GloballightFontColor forState:UIControlStateHighlighted];
        [addPictureBtn addTarget:self action:@selector(addPictureBtnDidClick:) forControlEvents:UIControlEventTouchUpInside];
        [_topView addSubview:addPictureBtn];
        
        [addPictureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_topView);
            make.right.equalTo(_topView).offset(-10);
        }];
        
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"addPicture"]];
        [_topView addSubview:imageView];
        
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_topView);
            make.right.equalTo(addPictureBtn.mas_left).offset(-8);
        }];
    }
    return _topView;
}


-(WPMinePlaceholderTextView *)textView
{
    if (_textView == nil)
    {
        
        _textView = [[WPMinePlaceholderTextView alloc] init];
        _textView.placeholder = @"请填写并上传处方单、检验单、收费单、X光照等单据";
        _textView.font = [UIFont systemFontOfSize:15];
        _textView.textColor = GLobalFontColor;
        _textView.delegate = self;
        
        //UITextView 中的 layoutManager(NSLayoutManager) 的是否非连续布局属性，默认是 YES，设置为 NO 后 UITextView 就不会再自己重置滑动了。
        
        _textView.allowsEditingTextAttributes = YES;
        _textView.contentInset = UIEdgeInsetsMake(4, 4, 4, -4);
        [self.bgView addSubview:_textView];
        
        [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self.bgView);
            make.bottom.equalTo(self.bgView);
            make.top.equalTo(self.topView.mas_bottom);
        }];
    }
    return _textView;
}

-(UILabel *)labelWith:(NSString *)title
{
    UILabel *label = [UILabel new];
    label.text = title;
    label.textColor = GLobalFontColor;
    label.font = [UIFont systemFontOfSize:15];
    return label;
}

-(UITextField *)textFieldWithPlaceholder:(NSString *)placeholder
{
    UITextField *field = [[UITextField alloc] init];
    field.placeholder = placeholder;
    field.font = [UIFont systemFontOfSize:15];
    field.textColor = GLobalFontColor;
    field.clearButtonMode = UITextFieldViewModeWhileEditing;
    return field;
}

#pragma mark - TZImagePickerController

- (void)pushImagePickerController {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:self];
    
#pragma mark - 四类个性化设置，这些参数都可以不传，此时会走默认设置
    
    // 1.如果你需要将拍照按钮放在外面，不要传这个参数
    imagePickerVc.allowTakePicture = YES; // 在内部显示拍照按钮
    
    // 3. 设置是否可以选择视频/图片/原图
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = YES;
    
    // 4. 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate = NO;
    
#pragma mark - 到这里为止
    
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
        
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

#pragma mark - UITextView的代理方法
//- (void)textViewDidChangeSelection:(UITextView *)textView
//{
//    NSInteger location = textView.selectedRange.location;
//    NSAttributedString *att = textView.attributedText;
//    
//    if(location == att.length)
//    {
//        return ;
//    }
//    
//    //遍历
//    [att enumerateAttribute:NSAttachmentAttributeName inRange:NSMakeRange(0, att.length) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) {
//        
//        if (range.location == location)
//        {
//            //检查类型是否是自定义NSTextAttachment类
//            if (value && [value isKindOfClass:[WPCustomTextAttachment class]])
//            {
//                textView.selectedRange = NSMakeRange(location-1, 0);
//            }
//        }
//    }];
//}

#pragma mark - 按钮响应事件方法
-(void)backBtnDidClick
{
    [self.view endEditing:YES];
    
    //    [IQKeyboardManager sharedManager].enable = YES;
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)saveBtnDidClick:(UIButton *)btn
{
    if (!(self.diseaseTextField.text.length && self.doctorTextField.text && self.hospitalTextField.text && ![self.treamentStateBtn.titleLabel.text isEqualToString:@"治疗状态"]))
    {
        [self showInfoStatus:@"请把以上基本信息补充完整"];
        return ;
    }
    
    if (!self.textView.attributedText.length)
    {
        [self showInfoStatus:@"诊断单内容不能为空"];
        return ;
    }
    
    NSString *url = @"record/editReturnVisit.do";
    
    // 1. 发送带有图片标志的纯文本到服务器
    NSString *textString = [self textStringWithSymbol:@"[图片]" attributeString:self.textView.attributedText];
    //去掉多余的图片前的换行符
    textString = [self deleteNewlineWith:textString];
    
    [self showWithStatus:@"正在保存"];
    
    WPEditeModel *editeModel = [WPEditeModel new];
    editeModel.recordId = self.mrModel.id;
    
    editeModel.rank = self.newRank;
    editeModel.descp = textString;
    
    //新添加的
    editeModel.name = self.diseaseTextField.text;
    editeModel.doctor = self.doctorTextField.text;
    editeModel.hospital = self.hospitalTextField.text;
    editeModel.cureStatus = self.treamentStateBtn.titleLabel.text;
    editeModel.type = self.ZXBtn.titleLabel.text;
    
    if (![self.timeBtn.titleLabel.text isEqualToString:@"请输入诊断时间"])
    {
        editeModel.treatmentTime = self.timeBtn.titleLabel.text;
    }
    else
    {
        editeModel.treatmentTime = @"";
    }
    
    NSString *JSONStr = [editeModel yy_modelToJSONString];
    NSDictionary *dict = @{@"json":JSONStr};
    
    if (self.photos.count)
    {
        for (NSNumber *index in self.imageNameArr)
        {
            int i = index.intValue-1;
            if (i >= 0)
            {
                UIImage *image = self.photos[i];
                NSString *totalPath = [documentPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%lu.jpg",(unsigned long)i+1]];
                
                NSData *data = UIImageJPEGRepresentation(image, 0.6);
                [data writeToFile:totalPath atomically:NO];
                
                NSURL *imageURL = [NSURL fileURLWithPath:totalPath];
                
                [self.pathArr addObject:imageURL];
            }
        }
    }
    
    [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        for (NSURL *imageURL in self.pathArr)
        {
            [formData appendPartWithFileURL:imageURL name:@"file" error:nil];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self dismiss];
        if([responseObject[@"result"] isEqualToString:@"success"])
        {
            [self showSuccessInfoWithStatus:@"保存成功"];
            
            WPReturnListModel *model = [WPReturnListModel yy_modelWithDictionary:responseObject[@"detail"]];
            
            if (self.isSaved)
            {
                
                NSInteger index = self.mrModel.returnVisit_list.count;
                [(NSMutableArray *)self.mrModel.returnVisit_list replaceObjectAtIndex:index-1 withObject:model];
            }
            else
            {
                NSMutableArray *returnListArr = [NSMutableArray arrayWithArray:self.mrModel.returnVisit_list];
                [returnListArr addObject:model];
                self.mrModel.returnVisit_list = returnListArr;
            }
            
            self.isSaved = YES;
            //刷新
            if (self.reloadBlock)
            {
                self.reloadBlock();
            }
        }
        else
        {
            //            考虑到账号过期的情况
            if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
            {
                // 账号过期
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"账号过期,请重新登录" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    
                    //账号过期,重新登录
                    WPMineLoginVC *vc = [WPMineLoginVC new];
                    [self presentViewController:[[UINavigationController alloc] initWithRootViewController:vc] animated:YES completion:nil];
                    
                    vc.successLoginBlock = ^
                    {
                        [self saveBtnDidClick:nil];
                    };
                }];
                [alertController addAction:sure];
                [self presentViewController:alertController animated:YES completion:nil];
            }
            else
            {
                [self showErrorInfoWithStatus:responseObject[@"detail"]];
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [self dismiss];
        [self showErrorInfoWithStatus:@"网络错误"];
    }];
}

-(void)timeBtnDidClick:(UIButton *)btn
{
    
    if (btn == self.treamentStateBtn)
    {
        
        CGSize size = [self.treamentArr[0] sizeWithMaxSize:CGSizeMake(MAXFLOAT, MAXFLOAT) font:14];
        YBPopupMenu *menu = [YBPopupMenu showRelyOnView:btn titles:self.treamentArr icons:nil menuWidth:size.width + 35 delegate:self];
        menu.fontSize = 14;
        menu.textColor = GLobalFontColor;
    }
    else if(btn == self.ZXBtn)
    {
        CGSize size = [self.ZXArr[0] sizeWithMaxSize:CGSizeMake(MAXFLOAT, MAXFLOAT) font:14];
        self.ZXPopupMenu = [YBPopupMenu showRelyOnView:self.ZXBtn supView:self.baseInfoView titles:self.ZXArr icons:nil menuWidth:size.width+35 delegate:self];
        self.ZXPopupMenu.fontSize = 14;
        self.ZXPopupMenu.textColor = GLobalFontColor;
    }
    else
    {
        [self.view endEditing:YES];
        
        // 创建日期选择器
        HMDatePicker *pickerView = [HMDatePicker datePicker];
        // 设置代理
        pickerView.delegate = self;
        // 设置datePicker当前显示的时间
        pickerView.currentDate = [NSDate date];
        // 显示
        [pickerView show];
    }
}

-(void)setNewRank:(NSInteger)newRank
{
    _newRank = newRank;
    
    self.timeLabel.text = [NSString stringWithFormat:@"%@诊时间:",self.timesArr[newRank-1]];
}

#pragma mark - 弹出视图的代理方法
- (void)ybPopupMenuDidSelectedAtIndex:(NSInteger)index ybPopupMenu:(YBPopupMenu *)ybPopupMenu
{
    if (ybPopupMenu == self.ZXPopupMenu)
    {
        [self.ZXBtn setTitle:self.ZXArr[index] forState:UIControlStateNormal];
    }
    else
    {
        [self.treamentStateBtn setTitle:self.treamentArr[index] forState:UIControlStateNormal];
        [self.treamentStateBtn setTitleColor:GLobalFontColor forState:UIControlStateNormal];
    }
}

// 键盘弹出时调用方法
-(void)keyboardDidShow:(NSNotification *)notification
{
    //获取键盘的高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    CGFloat height = keyboardRect.size.height;
    self.keyboardH = height;
    
    // 获取压缩后的高度
    double duration = [[notification.userInfo objectForKey: UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIImage *ZDImage = [UIImage imageNamed:@"zhenduan"];
    
    // 获取压缩后的高度
//    CGFloat h = self.oldFrame.size.height - height;
    //    // 定义一个新的矩形，具有压缩后的高度
//    CGRect rect = CGRectMake(self.oldFrame.origin.x, self.oldFrame.origin.y, self.oldFrame.size.width, h);
    
    if ([self.textView isFirstResponder])
    {
        
        [UIView animateWithDuration:duration animations:^{
            
            self.bgView.frame  = CGRectMake(0, 64-(162+ZDImage.size.height), SCREEN_WIDTH, SCREEN_HEIGHT-64+(162+ZDImage.size.height)-height);
            
            // 赋值给 textView
            //            self.textView.frame = rect;
            
        } completion:^(BOOL finished) {
            
//            [self.textView scrollRectToVisible:CGRectMake(0, self.textView.contentSize.height-15, self.textView.contentSize.width, 10) animated:NO];
        }];
    }
    
}

//当键盘出现或改变时调用
-(void)keyboardWillHide:(NSNotification *)aNotification
{
    // 取得键盘的动画时间，这样可以在视图上移的时候更连贯
    double duration = [[aNotification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    //    if (self.textView.contentSize.height <= self.textView.frame.size.height)
    //    {
    [UIView animateWithDuration:duration animations:^{
        
        self.bgView.frame = CGRectMake(0, 64, self.view.frame.size.width, SCREEN_HEIGHT-64);
    }];
    //    }
    //    else
    //    {
    //        [UIView animateWithDuration:duration animations:^{
    //
    //            self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height+self.keyboardH);
    //        }];
    //    }
}

- (void)datePickerDidValueChanged:(HMDatePicker *)datePicker
{
    NSDate *date = datePicker.datePicker.date;
    NSString *dateStr = [[WPDateFormatterManager sharedManager] stringFromDateWithDate:date format:@"yyyy-MM-dd"];
    [self.timeBtn setTitle:dateStr forState:UIControlStateNormal];
    [self.timeBtn setTitleColor:GLobalFontColor forState:UIControlStateNormal];
}

-(void)addPictureBtnDidClick:(UIButton *)btn
{
    [self.view endEditing:YES];
    
    [self pushImagePickerController];
}

#pragma mark - TZImagePickerControllerDelegate

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    
    //这里拿到选择的图片
    //这里可以拿到选择的图片
    
    NSUInteger location = self.textView.selectedRange.location;
    
    NSMutableAttributedString *mutableAttr = [self.textView.attributedText mutableCopy];
    
    
    // 1. 保存图片与图片的location
    for (UIImage *image in photos)
    {
        [self.photos addObject:image];
        
        [mutableAttr insertAttributedString:[[NSAttributedString alloc] initWithString:@"\n"] atIndex:location];
        location++;
        
        // 2. 将图片插入到富文本中
        WPCustomTextAttachment *attach = [[WPCustomTextAttachment alloc] init];
        attach.image = image;
        attach.url = [NSString stringWithFormat:@"%zd.jpg",self.index];
        attach.index = self.index;
        
        CGFloat imageRate = image.size.width / image.size.height;
        attach.bounds = CGRectMake(0, MARGIN*0.5, self.textView.frame.size.width - MARGIN, (self.textView.frame.size.width - MARGIN) / imageRate);
        NSAttributedString *imageAttr = [NSAttributedString attributedStringWithAttachment:attach];
        [mutableAttr insertAttributedString:imageAttr atIndex:location];
        
        location++;
        
        self.index++;
    }
    
    [mutableAttr insertAttributedString:[[NSAttributedString alloc] initWithString:@"\n"] atIndex:location];
    location++;
    
    self.textView.attributedText = mutableAttr;
    self.textView.font = [UIFont systemFontOfSize:15];
    self.textView.selectedRange = NSMakeRange(location, 0);
    
    [self.textView becomeFirstResponder];
    
}

/** 将富文本转换为带有图片标志的纯文本*/
- (NSString *)textStringWithSymbol:(NSString *)symbol attributeString:(NSAttributedString *)attributeString{
    
    NSString *string = attributeString.string;
    
    string = [self stringDeleteString:@"\n" frontString:symbol inString:string];
    //最终纯文本
    NSMutableString *textString = [NSMutableString stringWithString:string];
    //替换下标的偏移量
    __block NSUInteger base = 0;
    
    //遍历
    [attributeString enumerateAttribute:NSAttachmentAttributeName inRange:NSMakeRange(0, attributeString.length)
                                options:0
                             usingBlock:^(id value, NSRange range, BOOL *stop) {
                                 //检查类型是否是自定义NSTextAttachment类
                                 if (value && [value isKindOfClass:[WPCustomTextAttachment class]]) {
                                     
                                     WPCustomTextAttachment *att = (WPCustomTextAttachment *)value;
                                     [self.imageNameArr addObject:@(att.index)];
                                     
                                     NSString *replaceStr = [NSString stringWithFormat:@"[%@]",att.url];
                                     //替换
                                     [textString replaceCharactersInRange:NSMakeRange(range.location + base, range.length) withString:replaceStr];
                                     //增加偏移量
                                     base += (replaceStr.length - 1);
                                 }
                             }];
    
    return textString;
}

/** 删除字符串*/
- (NSString *)stringDeleteString:(NSString *)deleteString frontString:(NSString *)frontString inString:(NSString *)inString{
    
    NSArray *ranges = [self rangeOfSymbolString:frontString inString:inString];
    NSMutableString *mutableString = [inString mutableCopy];
    NSUInteger base = 0;
    for (NSString *rangeString in ranges) {
        NSRange range = NSRangeFromString(rangeString);
        [mutableString deleteCharactersInRange:NSMakeRange(range.location - deleteString.length + base, deleteString.length)];
        base -= deleteString.length;
    }
    return [mutableString copy];
}

#pragma mark - commonly used
/** 统计文本中所有图片资源标志的range*/
- (NSArray *)rangeOfSymbolString:(NSString *)symbol inString:(NSString *)string {
    
    NSMutableArray *rangeArray = [NSMutableArray array];
    NSString *string1 = [string stringByAppendingString:symbol];
    NSString *temp;
    for (int i = 0; i < string.length; i ++) {
        
        temp = [string1 substringWithRange:NSMakeRange(i, symbol.length)];
        if ([temp isEqualToString:symbol]) {
            NSRange range = {i, symbol.length};
            [rangeArray addObject:NSStringFromRange(range)];
        }
    }
    return rangeArray;
}

//删除[]前的换行符
-(NSString *)deleteNewlineWith:(NSString *)str
{
    NSString *mutableStr = [NSString stringWithFormat:@"%@",str];
    // 表情的规则
    NSString *emotionPattern = @"\\[.*\\]";
    // 使用系统的正则类来遍历
    NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:emotionPattern options:0 error:nil];
    
    // 2.测试字符串
    NSArray *results = [regex matchesInString:str options:0 range:NSMakeRange(0, str.length)];
    // 3.遍历结果
    for (NSTextCheckingResult *result in results)
    {
        NSString *subString = [NSString stringWithFormat:@"\n%@",[str substringWithRange:result.range]];
        mutableStr = [mutableStr stringByReplacingOccurrencesOfString:subString withString:[str substringWithRange:result.range]];
        
        subString = [NSString stringWithFormat:@"%@\n",[str substringWithRange:result.range]];
        mutableStr = [mutableStr stringByReplacingOccurrencesOfString:subString withString:[str substringWithRange:result.range]];
    }
    return mutableStr;
}

-(void)textViewDidBeginEditing:(UITextView *)textView
{
//    UIImage *ZDImage = [UIImage imageNamed:@"zhenduan"];
    
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
//    UIImage *ZDImage = [UIImage imageNamed:@"zhenduan"];
//    if (scrollView.contentOffset.y > 0)
//    {
//        if (self.bgView.frame.origin.y > 0)
//        {
//            [UIView animateWithDuration:0.25 animations:^{
//                
//                self.bgView.frame  = CGRectMake(0, 64-(162+ZDImage.size.height), SCREEN_WIDTH, SCREEN_HEIGHT-64+162+ZDImage.size.height);
//            }];
//        }
//    }
    
    if(scrollView.contentOffset.y < 0)
    {
        if (self.bgView.frame.origin.y < 0)
        {
            [self.textView resignFirstResponder];
            
            [UIView animateWithDuration:0.25 animations:^{
                
                self.bgView.frame  = CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64);
            }];
        }
    }
}

/*-----------------------------------------------------------------------------*/

#pragma mark - 懒加载
- (NSMutableArray *)photos{
    if (!_photos) {
        _photos = [NSMutableArray array];
    }
    return _photos;
}

- (NSMutableArray *)locations{
    if (!_locations) {
        _locations = [NSMutableArray array];
    }
    return _locations;
}

-(NSMutableArray *)pathArr
{
    if (_pathArr == nil)
    {
        _pathArr = [NSMutableArray array];
    }
    return _pathArr;
}

-(NSMutableArray *)imageNameArr
{
    if (_imageNameArr == nil)
    {
        _imageNameArr = [NSMutableArray array];
    }
    return _imageNameArr;
}

-(NSArray *)treamentArr
{
    if (_treamentArr == nil)
    {
        _treamentArr = [NSArray arrayWithObjects:@"未治愈",@"治疗中",@"已治愈", nil];
    }
    return _treamentArr;
}
-(NSArray *)ZXArr
{
    if (_ZXArr == nil)
    {
        _ZXArr = [NSArray arrayWithObjects:@"中医",@"西医", nil];
    }
    return _ZXArr;
}

-(NSArray *)timesArr
{
    if (_timesArr == nil)
    {
        _timesArr = [NSArray arrayWithObjects:@"一",@"二",@"三",@"四",@"五",@"六",@"七",@"八",@"九",@"十",@"十一",@"十二", nil];
    }
    return _timesArr;
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end

